package service

import (
	"AiBus/global"
	"AiBus/model"
	"AiBus/request"
	"AiBus/utils"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"time"
)

func SMCode(c *gin.Context, req request.SMCodeReq) {

	user := model.User{}

	//短信验证码登录
	err := global.App.DB.Where("nick_name=?", req.Mobile).First(&user).Error
	grants := utils.Credit_grants()

	if err != nil {
		UID := uuid.New() // 生成用户ID
		// 没有该用户就直接注册

		userInfo := model.User{
			OpenId:    UID.String(),
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
			NickName:  req.Mobile,
		}

		err = global.App.DB.Create(&userInfo).Error
		if err != nil {
			utils.Fail(c, 400, "登录失败，账号或密码错误")
		} else {
			token, err := utils.CreateToken(UID.String())
			now := time.Now().Unix()
			if err != nil {
				//global..Log.Error(err.Error())
				utils.Fail(c, 400, "登录失败，账号或密码错误")
			} else {

				UserInfo := map[string]interface{}{

					"open_id":       UID.String(),
					"avatarUrl":     user.AvatarUrl,
					"nick_name":     userInfo.NickName,
					"gender":        userInfo.Gender,
					"is_vip":        userInfo.IsVIP,
					"grants":        grants,
					"token":         token,
					"created_at":    userInfo.CreatedAt.Format(time.DateTime),
					"expire_at":     now + global.App.Configuration.Server.AccessExpire,
					"refresh_after": now + global.App.Configuration.Server.AccessExpire/2,
				}
				utils.Success(c, 0, UserInfo)
			}
		}
	} else {

		token, err := utils.CreateToken(user.OpenId)
		now := time.Now().Unix()
		if err != nil {

			utils.Fail(c, 400, "登录失败，账号或密码错误")
		} else {
			UserInfo := map[string]interface{}{
				"open_id":       user.OpenId,
				"avatarUrl":     user.AvatarUrl,
				"nick_name":     user.NickName,
				"gender":        user.Gender,
				"is_vip":        user.IsVIP,
				"grants":        grants,
				"token":         token,
				"created_at":    user.CreatedAt.Format(time.DateTime),
				"expire_at":     now + global.App.Configuration.Server.AccessExpire,
				"refresh_after": now + global.App.Configuration.Server.AccessExpire/2,
			}
			utils.Success(c, 0, UserInfo)
		}
	}

}
